package com.wangzhixuan.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.javassist.runtime.DotClass;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wangzhixuan.commons.report.excel.EasyExcel;
import com.wangzhixuan.mapper.UserMapper;
import com.wangzhixuan.mapper.UserRoleMapper;
import com.wangzhixuan.service.GetUserInfoService;
import com.wangzhixuan.task.DocDto;
import com.wangzhixuan.task.ExpVipUser;
import com.wangzhixuan.task.ItbUser;
import com.wangzhixuan.task.OrderInfo;
import com.wangzhixuan.task.UserDoc;
import com.wangzhixuan.task.VipUser;
import com.wangzhixuan.test.excel.ExpOrder;
import com.wangzhixuan.test.excel.UserInfo;




@Service
public class GetUserInfoServiceImpl implements GetUserInfoService {
	
	
	 	@Autowired
	    private UserMapper userMapper;
	    @Autowired
	    private UserRoleMapper userRoleMapper;
	    
	    
	    private static final String start_time = "2018-04-01 00:00:00";// 开始时间
	    private static final String end_time = "2018-06-30 23:59:59";// 结束时间
	    private static final int city = 420100;
	    
	    private static String filenameTemp;
	    
	    
	    
		/**
		 *  导出用户信息
		 *  用户ID

			用户注册时间
			
			是否为VIP
			
			下单数量、
			
			我的作品数量、作品品类、时间区间
			
			加入购物车数量、品类
		 */
		public void exportUserInfo(Map<String, Object> parm) {
			Map<String, Object> param =new HashMap<String, Object>();
			param.put("start_time",start_time);
			param.put("end_time",end_time);
			param.put("city",city);
			
			List<UserInfo> li = new ArrayList<UserInfo>();
			EasyExcel fastExcel = null;
			try {
				fastExcel = new EasyExcel("C://Users/zhaojixing/Desktop/data.xlsx");
			} catch (InvalidFormatException | IOException e) {
				e.printStackTrace();
			}
			
			
			List<ItbUser> list = userMapper.getItbUserInfo(param);
			for (ItbUser itbUser : list) {
				UserInfo user = new UserInfo();
				
				Map<String, Object> p1 = new HashMap<String, Object>();
				p1.put("user_id",itbUser.getUser_id());
				
				List<UserDoc> type = userMapper.getUserDocType(p1);
				StringBuilder st = new StringBuilder();
				for (UserDoc userDoc : type) {
					st.append(userDoc.getDocTypeName()+":"+userDoc.getTypeCnt()+"个\n");
				}
				
				
				List<UserDoc> liThumb = userMapper.getUserDocThumb(p1);
				int len = liThumb.size();
				StringBuilder stThumb = new StringBuilder();
				StringBuilder stTime = new StringBuilder();
				for (UserDoc userDoc : liThumb) {
					stThumb.append(userDoc.getThumb()+"\n");
					stTime.append(userDoc.getCreate_time()+"\n");
				}
				
				
				List<UserDoc> shopType = userMapper.getUserShopType(p1);
				StringBuilder shopSt = new StringBuilder();
				for (UserDoc userDoc : shopType) {
					shopSt.append(userDoc.getShopTypeName()+":"+userDoc.getTypeCnt()+"个\n");
				}
				
			   List<UserDoc> liShopThumb = userMapper.getUserShopThumb(p1);// 购物车图片
			   int shopLen = liShopThumb.size();
			   StringBuilder shopThmbSt = new StringBuilder();
			   for (UserDoc userDoc : liShopThumb) {
				   shopThmbSt.append(userDoc.getThumb()+"\n");
				
			   }
				
				
				// 导出数据
				user.setUserId(itbUser.getUser_id());
				user.setRegisterTime(itbUser.getCreate_time());
				user.setVipDesc(itbUser.getDesc());
				user.setVipCret(itbUser.getVipCret());
				user.setVipEipt(itbUser.getVipEipt());
				user.setBuyOrdCnt(itbUser.getBuyOrdCnt());
				user.setUserDocCnt(len);// 作品数
				user.setUserDocType(st.toString());
				user.setTimeRange(stTime.toString());
				user.setShopDocCnt(shopLen);
				user.setShopDocType(shopSt.toString());// 购物车品类
				
				
//				user.setDocUrls(stThumb.toString());
//				user.setShopDocType("海报");
//				user.setShopDocUrls("http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U691926/2018/09/17/092051367_YuzDUxefP8crJCn7Uiyq/0.jpg");
				
				
				// 个人中心作品图片
				GenerateFile(itbUser.getUser_id(), 1);
				try {
					writeTxtFile(stThumb.toString());
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
				
				
				// 生成购物车 图片文件
				GenerateFile(itbUser.getUser_id(), 2);
				try {
					writeTxtFile(shopThmbSt.toString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				li.add(user);
			}
			
			
			fastExcel.createExcel(li);
			try {
				fastExcel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		
		/**
		 * 生成文件
		 */
		public static void GenerateFile(long userId,int type){
			
			final String docName = "_docName";
			final String shopName = "_shopName_";
			final String pathName = "C://Users/zhaojixing/Desktop/thumb/";
			
			if (type == 1){// 生成作品链接txt
				filenameTemp = pathName+userId+docName+".txt";
			} else {
				filenameTemp = pathName+userId+shopName+".txt";
			}
			
			
			File file = new File(filenameTemp);
			try{
				if (!file.exists()) {
					file.createNewFile();
				}
			}catch(Exception e){
				System.out.println(e);
			}
		}
	    
		
		/**
		 * 写文件
		 * 
		 * @param newStr
		 *            新内容
		 * @throws IOException
		 */
		public static boolean writeTxtFile(String newStr) throws IOException {
			// 先读取原有文件内容，然后进行写入操作
			boolean flag = false;
			String filein = newStr + "\r\n";
			String temp = "";
	 
			FileInputStream fis = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
	 
			FileOutputStream fos = null;
			PrintWriter pw = null;
			try {
				// 文件路径
				File file = new File(filenameTemp);
				// 将文件读入输入流
				fis = new FileInputStream(file);
				isr = new InputStreamReader(fis);
				br = new BufferedReader(isr);
				StringBuffer buf = new StringBuffer();
	 
				// 保存该文件原有的内容
				for (int j = 1; (temp = br.readLine()) != null; j++) {
					buf = buf.append(temp);
					// System.getProperty("line.separator")
					// 行与行之间的分隔符 相当于“\n”
					buf = buf.append(System.getProperty("line.separator"));
				}
				buf.append(filein);
	 
				fos = new FileOutputStream(file);
				pw = new PrintWriter(fos);
				pw.write(buf.toString().toCharArray());
				pw.flush();
				flag = true;
			} catch (IOException e1) {
				// TODO 自动生成 catch 块
				throw e1;
			} finally {
				if (pw != null) {
					pw.close();
				}
				if (fos != null) {
					fos.close();
				}
				if (br != null) {
					br.close();
				}
				if (isr != null) {
					isr.close();
				}
				if (fis != null) {
					fis.close();
				}
			}
			return flag;
		}

		
		
		/**
		* 	订单ID
		*
		*	订单品类、具体金额、时间 
		*	
		&	订单作品详情
		*	
		&	收件地址、电话、公司名称
		*	
		&	支付状态：正常
		*/
		public void exportUserOrder(Map<String, Object> parm) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("start_time",start_time);
			param.put("end_time",end_time);
			param.put("city",city);
			
			EasyExcel fastExcel = null;
			try {
				fastExcel = new EasyExcel("C://Users/zhaojixing/Desktop/order.xlsx");
			} catch (InvalidFormatException | IOException e) {
				e.printStackTrace();
			}
			
			List<ExpOrder> exp = new ArrayList<ExpOrder>();
			
			List<OrderInfo> list = userMapper.getOrderInfo(param);
			for (OrderInfo orderInfo : list) {
				Map<String, Object> p1 = new HashMap<String, Object>();
				p1.put("order_id", orderInfo.getOrder_id());
				
				List<DocDto> lisDoc = userMapper.getOrderDoc(p1);
				StringBuilder docType = new StringBuilder();
				for (DocDto docDto : lisDoc) {
					docType.append(docDto.getDocTypeName()+":"+docDto.getDocTypeCnt()+"个\n");
				}
				
				List<DocDto> lisThumb = userMapper.getOrderDocThumb(p1);
				StringBuilder st = new StringBuilder();
				for (DocDto docDto : lisThumb) {
					st.append(docDto.getThumb()+"\n");
				}
				
				ExpOrder obj = new ExpOrder();
				obj.setUserId(orderInfo.getUser_id());
				obj.setOrder_id(orderInfo.getOrder_id());
				obj.setCreate_time(orderInfo.getCreate_time()+"\n"+orderInfo.getFinish_time());
//				obj.setFinish_time(orderInfo.getFinish_time());
				obj.setTotalPrice(orderInfo.getTotal_fee()/100);
				obj.setMobile(orderInfo.getMobile());
				obj.setName(orderInfo.getName());
				obj.setDetail(orderInfo.getDetail());
				obj.setDocType(docType.toString());
				obj.setDocThumb(st.toString());
				
				exp.add(obj);
			}
			

			fastExcel.createExcel(exp);
			try {
				fastExcel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}


		
		/**
		 * 	用户：用户ID 个人中心作品时间区间（线上） 作品分类 作品链接（图片）
		 */
		public void exportVipUserInfo(Map<String, Object> parm) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("start_time", "2018-10-01 00:00:00");
			param.put("end_time", "2018-10-29 23:59:59");
			
			List<ExpVipUser> list = new ArrayList<ExpVipUser>();
			EasyExcel fastExcel = null;
			try {
				fastExcel = new EasyExcel("C://Users/zhaojixing/Desktop/vip.xlsx");
			} catch (InvalidFormatException | IOException e) {
				e.printStackTrace();
			}
			
			List<VipUser> vipUser = userMapper.getVipUserInfo(param);
			for (VipUser vipUser2 : vipUser) {
				ExpVipUser user =new ExpVipUser();
				
				Map<String, Object> p1 = new HashMap<String, Object>();
				p1.put("user_id",vipUser2.getUser_id());
				
				List<UserDoc> type = userMapper.getUserDocType(p1);// 作品品类
				StringBuilder st = new StringBuilder();
				for (UserDoc userDoc : type) {
					st.append(userDoc.getDocTypeName()+":"+userDoc.getTypeCnt()+"个\n");
				}
				
				
				List<UserDoc> liThumb = userMapper.getUserDocThumb(p1);// 作品封面图
				int len = liThumb.size();
				StringBuilder stThumb = new StringBuilder();
				StringBuilder stTime = new StringBuilder();
				for (UserDoc userDoc : liThumb) {
					stThumb.append(userDoc.getThumb()+"\n");
					stTime.append(userDoc.getCreate_time()+"\n");
				}
				
				user.setUserId(vipUser2.getUser_id());
				user.setRegisterTime(vipUser2.getRegisterTime());
				user.setTimeRange(String.valueOf(stTime));
				user.setVipDesc(vipUser2.getDesc());
				user.setVipCret(vipUser2.getCreate_time());
				user.setUserDocType(String.valueOf(st));
				user.setUserDocCnt(len);
				
				// 个人中心作品图片
				GenerateFile(vipUser2.getUser_id(), 1);
				try {
					writeTxtFile(stThumb.toString());
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
				
				list.add(user);
			}
			
			fastExcel.createExcel(list);
			try {
				fastExcel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
}
